/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, { ProFormUploadButton, ProFormTextArea } from '@ant-design/pro-form';
import { upload, getList, saveVersionDescription } from '@/services/Other/packagePush';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { columns } from '@/components/_pages/other/utils/config';
import { useDebounceFn } from '@ant-design/pro-utils';
import type { ActionType } from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ConnectState } from '@/models/connect';
import { useSelector } from 'umi';
import styles from './index.less';
import { message, Tree, Button, Divider } from 'antd';

interface ImportCovProps {
  current: 'imp' | 'records' | string;
}

const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 16 },
};

const ImportCov: React.FC<ImportCovProps> = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const uploadFormRef = useRef<ProFormInstance>();
  const formRef = useRef<ProFormInstance>();
  const [limitList, setLimitList] = useState<any>([]);
  const [limitData, setLimitData] = useState<string[]>([]);

  const handleTreeCheck = (data: any) => {
    setLimitData(data.filter((item: any) => !!item));
  };

  const getVersionList = () => {
    return getList({}).then((res) => {
      const { data: { info = [] } = {} } = res;
      const limits = [
        {
          title: '全部版本号',
          key: '',
          children: info.map((item: any) => ({ title: item.id, key: item.id })),
        },
      ];
      setLimitList(limits);
      return { data: info };
    });
  };
  const onRefresh = useDebounceFn(async () => {
    actionRef.current?.reload();
  }, 300);
  const handleUpload = async (data: any) => {
    const formData = new FormData();
    const { file = [] } = data;
    formData.append('Filedata', file[0]?.originFileObj);
    const { code, msg } = await upload(formData);
    if (code == 0) {
      uploadFormRef.current?.resetFields();
      setLimitData([]);
      onRefresh.run();
      message.success('提交成功！');
    } else {
      message.error(`提交失败：${msg}`);
    }
  };
  const onFinish = async (data: any) => {
    if (limitData.length < 1) {
      message.error('请至少选择一个版本号');
      return;
    }
    const params = {
      ...data,
      id: limitData.join(','),
    };

    const { code, msg } = await saveVersionDescription(params);
    if (code == 0) {
      formRef.current?.resetFields();
      setLimitData([]);
      onRefresh.run();
      message.success('提交成功！');
    } else {
      message.error(`提交失败：${msg}`);
    }
  };

  const beforeUpload = () => false;

  return (
    <PageContainer className={styles.main}>
      <ProForm
        className={styles.ImportCov}
        formRef={uploadFormRef}
        layout={winSize === 'xs' ? 'horizontal' : 'inline'}
        {...layout}
        onFinish={handleUpload}
        submitter={{
          searchConfig: {
            submitText: '上传',
          },
        }}
      >
        <ProFormUploadButton
          className={styles.uploadButton}
          name='file'
          width='md'
          max={1}
          fieldProps={{
            beforeUpload,
          }}
          buttonProps={{
            type: 'primary',
          }}
          title='点击上传预发包'
          rules={[{ required: true, message: '请上传预发包' }]}
        />
      </ProForm>
      <Divider plain />
      <ProForm
        className={styles.ImportCov}
        formRef={formRef}
        layout='horizontal'
        {...layout}
        submitter={{
          render: (props) => [
            <Button
              onClick={() => {
                props.reset();
                setLimitData([]);
              }}
            >
              重置
            </Button>,
            <Button type='primary' onClick={props.submit}>
              提交
            </Button>,
          ],
        }}
        onFinish={onFinish}
      >
        <ProForm.Item label=' ' colon={false}>
          <Tree
            className={styles.ImportCov__tree}
            checkable
            treeData={limitList}
            expandedKeys={['']}
            defaultExpandAll
            checkedKeys={limitData}
            onCheck={handleTreeCheck}
          />
        </ProForm.Item>
        <ProFormTextArea
          label='版本描述'
          name='detail'
          rules={[{ required: true, message: '请输入版本描述' }]}
        />
      </ProForm>
      <DragTable>
        <ProTable
          actionRef={actionRef}
          rowKey='id'
          columns={columns}
          options={{
            fullScreen: false,
            reload: false,
            setting: false,
            density: false,
          }}
          toolBarRender={() => [
            <Button type='primary' onClick={onRefresh.run}>
              刷新
            </Button>,
          ]}
          search={false}
          request={getVersionList}
          pagination={false}
          scroll={{ x: 1200 }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default ImportCov;
